package server

import (
	"context"
	"fmt"
	"yk1/user-server/basic/config"
	__ "yk1/user-server/basic/proto"
	"yk1/user-server/model"
	"yk1/user-server/pkg"
	"yk1/user-server/validator"
)

type Server struct {
	__.UnsafeUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) AdministratorsAdd(_ context.Context, in *__.AdministratorsAddReq) (*__.AdministratorsAddResp, error) {
	administrators := model.Administrators{
		UserId:       in.UserId,
		PermissionId: in.PermissionId,
	}
	config.DB.Create(&administrators)

	return &__.AdministratorsAddResp{
		Id: int64(administrators.Id),
	}, nil
}
func (s *Server) RiderAdd(_ context.Context, in *__.RiderAddReq) (*__.RiderAddResp, error) {
	if !validator.IsValidMobile(in.Mobile) {
		return nil, fmt.Errorf("手机格式错误")
	}
	if validator.IsValidName(in.Name) {
		return nil, fmt.Errorf("姓名格式错误")
	}
	var rider model.Rider
	config.DB.Where("mobile = ?", in.Mobile).Find(&rider)
	if rider.Id != 0 {
		return nil, fmt.Errorf("手机号已存在")
	}
	a := model.Rider{
		UserId:    int32(in.UserId),
		Name:      in.Name,
		Mobile:    in.Mobile,
		IdCard:    in.IdCard,
		BikeNo:    in.BikeNo,
		StationId: in.StationId,
	}
	config.DB.Create(&a)
	_, err := pkg.SmnSend(in.Mobile, "欢迎加入骑手系统，请及时填写车辆信息")
	if err != nil {
		return nil, fmt.Errorf("短信发送失败")
	}

	return &__.RiderAddResp{
		Id: int64(rider.Id),
	}, nil
}
func (s *Server) MessageAdd(_ context.Context, in *__.MessageAddReq) (*__.MessageAddResp, error) {
	message := model.Message{
		UserId:  int32(in.UserId),
		Mobile:  in.Mobile,
		Message: in.Message,
	}
	config.DB.Create(&message)

	return &__.MessageAddResp{
		Id: int64(message.Id),
	}, nil
}
func (s *Server) CabinetAdd(_ context.Context, in *__.CabinetAddReq) (*__.CabinetAddResp, error) {
	cabinet := model.ExpressCabinet{
		Code:        in.Code,
		Address:     in.Address,
		Description: in.Description,
		StationId:   in.StationId,
	}
	config.DB.Create(&cabinet)
	A := fmt.Sprintf("CabinetAdd")
	_, err := config.Rdb.Set(context.Background(), A, cabinet, 0).Result()
	if err != nil {
		return nil, fmt.Errorf("添加redis失败")
	}
	return &__.CabinetAddResp{
		Id: int64(cabinet.Id),
	}, nil
}

func (s *Server) CabinetDetails(_ context.Context, in *__.CabinetDetailsReq) (*__.CabinetDetailsResp, error) {
	var Cabinet model.ExpressCabinet
	config.DB.Where("id = ?", in.Id).Find(&Cabinet)

	return &__.CabinetDetailsResp{
		Code:        Cabinet.Code,
		Address:     Cabinet.Address,
		Description: Cabinet.Description,
		StationId:   Cabinet.StationId,
		Status:      int64(Cabinet.Status),
	}, nil
}
func (s *Server) CabinetList(_ context.Context, in *__.CabinetListReq) (*__.CabinetListResp, error) {
	var cabinets []model.ExpressCabinet
	config.DB.Find(&cabinets)
	var cabinetList []*__.CabinetList
	for _, cabinet := range cabinets {
		list := __.CabinetList{
			Code:        cabinet.Code,
			Address:     cabinet.Address,
			Description: cabinet.Description,
			StationId:   cabinet.StationId,
			Status:      int64(cabinet.Status),
		}
		cabinetList = append(cabinetList, &list)

	}

	return &__.CabinetListResp{
		List: cabinetList,
	}, nil
}
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var user model.User
	config.DB.Where("mobile = ?", in.Mobile).Find(&user)
	if user.Id == 0 {
		return nil, fmt.Errorf("用户未注册")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}

	return &__.LoginResp{
		Id: int64(user.Id),
	}, nil
}

func (s *Server) DeliveryAdd(_ context.Context, in *__.DeliveryAddReq) (*__.DeliveryAddResp, error) {
	delivery := model.Delivery{
		RiderId:        int32(in.RiderId),
		TrackingNumber: in.TrackingNumber,
		CabinetId:      int32(in.CabinetId),
	}
	config.DB.Create(&delivery)
	key := "DeliveryAdd"
	_, err := config.Rdb.Info(context.Background(), key).Result()
	if err != nil {
		return nil, fmt.Errorf("添加redis失败")
	}

	return &__.DeliveryAddResp{
		Id: int64(delivery.Id),
	}, nil
}
func (s *Server) ModifyCabinetState(_ context.Context, in *__.ModifyCabinetStateReq) (*__.ModifyCabinetStateResp, error) {
	var cabinet model.ExpressCabinet
	config.DB.Where("id= ?", in.Id).Find(&cabinet)
	expressCabinet := model.ExpressCabinet{
		Id:     uint64(in.Id),
		Status: int32(in.Status),
	}
	config.DB.Updates(&expressCabinet)
	if in.Status == 1 {
		key := fmt.Sprintf("cabinet:%d", in.Status)
		config.Rdb.Info(context.Background(), key)
	}

	return &__.ModifyCabinetStateResp{
		Id: int64(expressCabinet.Id),
	}, nil
}

func (s *Server) DeliveryList(_ context.Context, in *__.DeliveryListReq) (*__.DeliveryListResp, error) {
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	var deliveries []model.Delivery
	config.DB.Offset(int(offset)).Limit(int(pageSize)).Order("create_time  DESC").Find(&deliveries)
	var deliveryList []*__.DeliveryList
	for _, list := range deliveryList {
		i := __.DeliveryList{
			Id:             list.Id,
			RiderId:        list.RiderId,
			TrackingNumber: list.TrackingNumber,
			CabinetId:      list.CabinetId,
		}
		deliveryList = append(deliveryList, &i)

	}
	return &__.DeliveryListResp{
		List: deliveryList,
	}, nil
}

func (s *Server) UserDetails(_ context.Context, in *__.UserDetailsReq) (*__.UserDetailsResp, error) {
	var user []model.User
	config.DB.Where("identity = ?", in.Identity).Find(&user)
	var c = 0
	for _, m := range user {
		key := fmt.Sprintf("user:%d", m.Identity)
		config.Rdb.Info(context.Background(), key)
		c++
	}
	return &__.UserDetailsResp{
		Quantity: int64(c),
	}, nil
}

func (s *Server) UserList(_ context.Context, in *__.UserListReq) (*__.UserListResp, error) {
	var user []model.User
	config.DB.Find(&user)
	var userList []*__.UserList
	for _, m := range user {
		list := __.UserList{
			Mobile:   m.Mobile,
			Identity: int64(m.Identity),
		}
		userList = append(userList, &list)
	}
	return &__.UserListResp{
		List: userList,
	}, nil
}

func (s *Server) DeliveryDetails(_ context.Context, in *__.DeliveryDetailsReq) (*__.DeliveryDetailsResp, error) {
	var delivery model.Delivery
	config.DB.Where("id = ?", in.Id).Find(&delivery)
	if delivery.State == 2 {
		pkg.SmnSend(string(delivery.RiderId), "你的快递已滞留")
	}
	return &__.DeliveryDetailsResp{
		Id:             int64(delivery.Id),
		RiderId:        int64(delivery.RiderId),
		TrackingNumber: delivery.TrackingNumber,
		CabinetId:      int64(delivery.CabinetId),
		Status:         int64(delivery.State),
	}, nil
}

func (s *Server) Greet(_ context.Context, in *__.StreamReq) (*__.StreamResp, error) {

	return &__.StreamResp{}, nil
}
